package cn.liccshop.core.service.shopCart.service;

import cn.liccshop.core.entity.ShopCart;
import cn.liccshop.core.service.shopCart.mapper.ShopCartMapper;
import cn.liccshop.core.service.shopCart.service.IShopCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiCC
 * @since 2019-04-30
 */
@Service
public class ShopCartServiceImpl extends ServiceImpl<ShopCartMapper, ShopCart> implements IShopCartService {

    @Override
    public List<Map<String, Object>> selectShopCartInfos(String userId) {
        List<Map<String, Object>> data = selectShopCartInfosUtils(baseMapper.selectShopCartInfos(userId));
        return data;
    }

    @Override
    public List<Map<String, Object>> getShopCartInfosAndOrderPro(String userId, List<String> ids) {
        if (CollectionUtils.isEmpty(ids)){
            /** ids为空 返回空 **/
            return null;
        }
        List<Map<String, Object>> infos = selectShopCartInfosUtils(baseMapper.selectShopCartInfos(userId));
        List<Map<String, Object>> data = new ArrayList<>();
        for (Map<String, Object> info : infos){
            for (String id : ids){
                if (info.get("id").equals(id)){
                    data.add(info);
                    break;
                }
            }
        }
        return data;
    }

    private List<Map<String, Object>> selectShopCartInfosUtils(List<Map<String, Object>> dataList) {
        List<Map<String, Object>> dataInfo = new ArrayList<>();
        if (CollectionUtils.isEmpty(dataList)){
            return null;
        }
        int index = 0;
        for (Map<String, Object> data : dataList){
            if (index == 0){
                /** 第一条数据 直接插入 **/
                dataInfo.add(data);
                /** 索引加1 **/
                index ++;
            } else {
                if (dataInfo.get((index-1)).get("id").equals(data.get("id"))){
                    /** 如果存入的最后一条数据ID与当前ID相同跳过该次循环 **/
                    continue;
                } else {
                    /** 如果存入的最后一条数据ID与当前ID不相同 存入数据 **/
                    dataInfo.add(data);
                    /** 索引加1 **/
                    index ++;
                }
            }
        }
        return dataInfo;
    }
}
